﻿using UnityEngine;
using System.Collections.Generic;
using ProtoBuf.Message;

namespace Room
{
    public class NetUnionFightActor : NetUnionFightBase
    {
        public Dictionary<long, InstUFPlayer> players = new Dictionary<long, InstUFPlayer>();
        public float MaxHp
        {
            get
            {
                if (players.ContainsKey(StaticData.playerData.playerId ))
                {
                    var fightInfo = players[StaticData.playerData.playerId ].fightInfo;
                    var maxHp = 0.0;
                    foreach(var max in fightInfo.maxHpPos)
                    {
                        maxHp += max;
                    }

                    return (float)maxHp;
                }
                else
                {
                    return 1;
                }
            }
        }

        #region current hp
        private float hp;
        public float currentHp
        {
            get
            {
                if (players.ContainsKey(StaticData.playerData.playerId))
                {
                    var fightInfo = players[StaticData.playerData.playerId].fightInfo;
                    var hp = 0.0;
                    foreach (var _hp in fightInfo.hpPos)
                    {
                        hp += _hp;
                    }
                    hp = Mathf.Clamp((float)hp, 0, MaxHp);
                    return (float)hp;
                }
                else
                    return 0f;
            }
            set
            {
                hp = value;
            }
        }
        #endregion

        #region Anger
        private float anger = 0f;
        public float Anger
        {
            set
            {
                this.anger = value;
            }
            get
            {
                if (players.ContainsKey(StaticData.playerData.playerId ))
                {
                    var fightInfo = players[StaticData.playerData.playerId ].fightInfo;
                    //这个数据不对，之后修改
                    anger = (float)fightInfo.fightPower;
                    return anger;
                }
                else
                {
                    return 0f;
                }
            }
        }
        #endregion

        public float reviveTime;

        public NetUnionFightActor(RoomUnionFight unionFight, RoomCharactorManager mgr, RoomNetUnionFight net)
            : base(unionFight, mgr, net)
        {
        }

        public override void Enter()
        {
            base.Enter();
            players.Clear();
        }

        public override void Leave()
        {
            base.Leave();
            players.Clear();
        }

        public override RoomCharactor CreateCharactor(long uuid)
        {
            var inst = players[uuid];
            charactorManager.CreateUnionOther(players[uuid]);
            var charactor = GetCharactor(uuid);
            players[uuid] = inst;
            return charactor;
        }

        public override void ClearCharactorData(long uuid)
        {
            base.ClearCharactorData(uuid);
            if (players.ContainsKey(uuid))
            {
                players.Remove(uuid);
            }
        }

        /// <summary>
        /// 玩家刷新
        /// </summary>
        /// <param name="msg"></param>
        public void ActorRefresh(SCUFPlayer msg)
        {
            for (int i = 0; i < msg.player.Count; i++)
            {
                var uuid = msg.player[i].guid;
                
                players[uuid] = msg.player[i];    
                var pos = new Vector3(msg.local[i].x, msg.local[i].y, msg.local[i].z);
                
                var charactor = GetCharactor(uuid,false);
                if (charactor == null)
                {
                    charactor = CreateCharactor(uuid);
                }
                

                Debug.Log("uuid=" + uuid + " " + "[ACTOR state]=[" + msg.player[i].state + "]"+" current pos:"+ pos);

                //强制刷新坐标
                UpdatePosition(uuid, pos);
                UpdateState(uuid, msg.player[i].state);
                ///加载buff
                foreach (var buff in msg.player[i].buffs)
                {
                    UpdateBuff(buff, uuid);
                }

                UpdateHp(players[uuid].fightInfo);
                if(uuid == StaticData.playerData.playerId)
                {
                    GetUI().Refresh();
                }
            }
        }


        /// <summary>
        /// 玩家死亡
        /// </summary>
        /// <param name="msg"></param>
        public void ActorDead(SCUFPlayerDead msg)
        {
            for(var index=0;index < msg.guid.Count;++index)
            {
                var uuid = msg.guid[index];
                UpdateState(uuid, (int)UnionActorState.Death);

                if (players.ContainsKey(uuid))
                {
                    var player = players[uuid];
                    for (int j = 0; j < player.fightInfo.hpPos.Count; ++j)
                    {
                        player.fightInfo.hpPos[j] = 0;
                    }

                    UpdateHp(player.fightInfo);
                }

                if (uuid == StaticData.playerData.playerId)
                {
                    reviveTime = (float)msg.reviveTime[index];
                    string itemId = msg.reviveItemId[index];
                    GetUI().SetReviveTime(reviveTime, itemId);
                }
            }
        }

        /// <summary>
        /// 玩家收集
        /// </summary>
        /// <param name="msg"></param>
        public void ActorStartCollect(SCUFPlayerCollect msg)
        {
            for(int i=0; i<msg.playerGuid.Count;++i)
            {
                var uuid = msg.playerGuid[i];
                var resUuid = msg.resGuid[i];

                var actor = GetCharactor(uuid);
                var res = GetCharactor(resUuid);
                var state = 0;
                if (actor != null && res != null)
                {
                    actor.transform.LookAt(res.transform);
                    state = (int)UnionActorState.Mining;
                }
                else if (actor != null && res == null)
                {
                    state = (int)UnionActorState.Stand;
                }
                
                UpdateState(uuid, state);
            }
        }

        /// <summary>
        /// 玩家结束收集
        /// </summary>
        /// <param name="msg"></param>
        public void ActorEndCollect(SCUFPlayerCollectEnd msg)
        {
            for (var i =0;i< msg.playerGuid.Count;++i)
            {
                var uuid = msg.playerGuid[i];
                var resUuid = msg.resGuid[i];
                var isUseOut = msg.isResExhausted[i] == BOOL.TRUE;

                UpdateState(uuid, (int)UnionActorState.Stand);

                if (isUseOut)
                {
                    net.netResource.ResourceDisappear(resUuid+"");
                }
            }
        }


        /// <summary>
        /// 玩家自己结束收集
        /// </summary>
        /// <param name="msg"></param>
        public void ActorEndCollectDetail(SCUFPlayerCollectEndDetail msg)
        {
            var uuid = msg.player.guid;
            players[uuid] = msg.player;
            if(msg.isResExhausted==BOOL.TRUE)
            {
                net.netResource.ResourceDisappear(msg.resGuid+"");
            }
            var charactor = GetCharactor(uuid);
            var state = (int)UnionActorState.Stand;
            UpdateState(uuid, state);
            
            GetUI().SetResBagNum((int)msg.player.ownRes.resourceNum);
        }

        /// <summary>
        /// 玩家开始使用物品
        /// </summary>
        /// <param name="msg"></param>
        public void ActorUseItem(SCUFPlayerUseItem msg)
        {
            foreach (var guid in msg.itemId)
            {
                var uuid = guid;
                var state = (int)UnionActorState.UseItem;
                UpdateState(uuid, state);
            }
        }

        /// <summary>
        /// 自己使用物品
        /// </summary>
        /// <param name="msg"></param>
        public void ActorUseItemDetail(SCUFPlayerUseItemDetail msg)
        {
            var uuid = msg.player.guid;
            players[uuid] = msg.player;
            BoxManager.CreatePopupTextBox(TableTextBlo.GetText("item_use_sucessful"));
            GetUI().UseItem(msg.itemId);
        }

        public void ActorStrengthenBuilding(SCUFStrengthBuilding msg)
        {
            //msg.type;
            //msg.level;
            BoxManager.CreatePopupTextBox(TableTextBlo.GetText("union_levelup_success"));
            net.SendCSUFStrengthBuildingInfo("");
            GetUI().Refresh();
        }

        /// <summary>
        /// 玩家出现
        /// </summary>
        /// <param name="msg"></param>
        public void ActorAppear(SCUFPlayerAppear msg)
        {
            for (int i = 0; i < msg.player.Count; ++i)
            {
                var player = msg.player[i];
                var pos = msg.local[i];

                var uuid = player.guid;

                players[uuid] = player;
                var _Pos = new Vector3(pos.x, pos.y, pos.z);
                
                CreateCharactor(uuid);
                
                UpdateState(uuid, player.state);
                UpdatePosition(uuid, _Pos);
                UpdateHp(player.fightInfo);
            }
        }

        /// <summary>
        /// 玩家消失
        /// </summary>
        /// <param name="msg"></param>
        public void ActorDisappear(SCUFPlayerDisappear msg)
        {
            foreach (var uuid in msg.guid)
            {
                DestroyCharactor(uuid);
            }
        }
        

        /// <summary>
        /// 玩家复活协议
        /// </summary>
        /// <param name="msg"></param>
        public void ActorRevive(SCUFPlayerRevive msg)
        {
            for (int i = 0; i < msg.guid.Count; ++i)
            {
                var uuid = msg.guid[i];
                var pos = msg.pos[i];
                var postion = new Vector3(pos.x, pos.y, pos.z);

                var state = (int)UnionActorState.Revive;
                UpdateState(uuid, state);
                UpdatePosition(uuid, postion);
                

                if (players.ContainsKey(uuid))
                {
                    var player = players[uuid];
                    for (int j = 0; j < player.fightInfo.hpPos.Count; ++j)
                    {
                        player.fightInfo.hpPos[j] = player.fightInfo.maxHpPos[j];
                    }
                    UpdateHp(player.fightInfo);
                }
            }
        }

        /// <summary>
        /// 玩家成功买道具
        /// </summary>
        /// <param name="msg"></param>
        public void ActorBuyItem(SCUFPlayerBuyItem msg)
        {

        }

        /// <summary>
        /// 玩家自己购买道具
        /// </summary>
        /// <param name="msg"></param>
        public void ActorBuyItemDetail(SCUFPlayerBuyItemDetail msg)
        {
            var uuid = msg.player.guid;
            players[uuid] = msg.player;
            GetUI().RefreshBag(msg.player.items);
            GetUI().SetContributionNum((int)msg.player.ownToken);
            BoxManager.CreatePopupTextBox(TableTextBlo.GetText("buy_success"));
            net.SendCSUFShopList("");
        }

        /// <summary>
        /// 玩家上交资源
        /// </summary>
        /// <param name="msg"></param>
        public void ActorUpResource(SCUFPlayerUpResource msg)
        {
            players[msg.player.guid] = msg.player;
            GetUI().SetResBagNum((int)msg.player.ownRes.resourceNum);
            BoxManager.CreatePopupTextBox(TableTextBlo.GetText("union_fight_recycleBin_sucessful"));
        }


        //连杀特效
        public void PlayerCcmpleteAchieve(SCUFPlayerCcmpleteAchieve msg)
        {
            var charactor = GetCharactor(StaticData.playerData.playerId);
            if(charactor != null)
            {
                var ai = charactor.ai as RCAIUnionSelf;
                ai.AchieveHorner(msg.type);
            }
        }


        public void ActorFightStart(SCUFPlayerFightBegin msg)
        {
            var uuid = msg.guid;
            UpdateState(uuid, (int)UnionActorState.Attack);
        }

        public void ActorFightEndDetail(SCUFPlayerFightEndDetail msg)
        {
            var uuid = msg.player.guid;
            if (uuid == StaticData.playerData.playerId)
            {
                players[uuid] = msg.player;
                var charactor = GetCharactor(uuid);
                if (charactor != null)
                {
                    var ai = charactor.ai as RCAIUnionActor;
                    if (ai.FightState())
                    {
                        UpdateState(uuid, (int)UnionActorState.Stand);
                    }
                    else
                    {
                        Debug.Log("[ERROR] charactor current state is " + ai.CurrState);
                    }
                }
            }
            else
            {
                Debug.LogError("[ERROR] current uuid is not mine my id:" + StaticData.playerData.playerId + " current id:" + uuid);
            }
        }

        public void ActorFightEnd(SCUFPlayerFightEnd msg)
        {
            var uuid = msg.guid;
            var charactor = GetCharactor(uuid);
            if (charactor != null)
            {
                var ai = charactor.ai as RCAIUnionActor;
                if (ai.FightState())
                {
                    UpdateState(uuid, (int)UnionActorState.Stand);
                }
                else
                {
                    Debug.Log("[ERROR] charactor current state is " + ai.CurrState);
                }
            }
        }

        public void ActorSpeed(SCUFMainPlayerSpeedChange msg)
        {
            var uuid = StaticData.playerData.playerId;
            var charactor = GetCharactor(uuid);
            charactor.SetSpeed((float)msg.speed);
            Debug.Log("[SPEED value] " + msg.speed);
        }

        public void ActorTransferBegin(SCUFBeginTransfer msg)
        {
            var uuid = msg.guid;
            UpdateState(uuid, (int)UnionActorState.Transfer);
        }

        public void ActorTransferEnd(SCUFEndTransfer msg)
        {
            var uuid = msg.guid;
            var pos = new Vector3(msg.target.x, msg.target.y, msg.target.z);
            UpdateState(uuid, (int)UnionActorState.Stand);
            UpdatePosition(uuid, pos);
        }
    }
}